import { AppSetting } from '../AppSetting';
import { Container } from '../Container';
import { BaseGui } from "../Services/BaseGui";
import { HelperTool } from '../Services/Common';
import { DataService } from "../Services/DataService";
export class ProjectGui extends BaseGui {
    title = `项目文件[${ProjectGui.name}]`;
    private DataService = Container.defineProperty(DataService);
    private AppSetting = Container.defineProperty(AppSetting);
    private defaultFileName = "newProject.json";
    async UpdateGui() {
        let fun = {
            newProject: () => {
                if (!window.confirm("确实要新建项目吗?"))
                    return;
                this.defaultFileName = "newProject.json";
                this.DataService.Data = {};
                this.DataService.OnDataChanged.dispatchEvent();
            },
            loadProject: () => {
                this.OpenFile((name, data) => {
                    this.defaultFileName = name;
                    this.DataService.Data = data;
                    this.DataService.OnDataChanged.dispatchEvent();
                });
            },
            loadProjectFromUrl: () => {
                this.OpenFromUrl((name, data) => {
                    this.defaultFileName = name;
                    this.DataService.Data = data;
                    this.DataService.OnDataChanged.dispatchEvent();
                });
            },
            saveProject: () => {
                this.SaveFile(this.DataService.Data, this.defaultFileName);
            }
        }
        let gui = this.gui;
        let updateGUI = () => {
            Array.from(gui.__controllers).forEach(_ => {
                gui.remove(_);
            })
            this.guiService.buildGUIByObject(this.gui, fun);
        }
        updateGUI();
    }
    Init(): void {
        if (this.AppSetting.StartSceneUrl) {
            setTimeout(() => {
                HelperTool.httpGet(this.AppSetting.StartSceneUrl).then((data) => {
                    this.defaultFileName = this.AppSetting.StartSceneUrl;
                    this.DataService.Data = data;
                    this.DataService.OnDataChanged.dispatchEvent();
                });
            }, 500);
        }
    }

    private OpenFile(callback: (name: string, data: any) => void) {
        //@ts-ignore
        let temp = window.showOpenFilePicker ? this.OpenFileByWindow() : this.OpenFileByDocument();
        temp.then((file) => {
            const reader = new FileReader();
            reader.onload = () => {
                const data = JSON.parse(reader.result as string);
                callback(file.name, data);
            };
            reader.readAsText(file);
        })
    }
    private OpenFromUrl(callback: (name: string, data: any) => void) {
        let fileName = window.prompt("OpenFromUrl", this.defaultFileName);
        if (!fileName) {
            return;
        }
        HelperTool.httpGet(fileName).then((data) => {
            callback(fileName!, data);
        });
    }
    private SaveFile(data: any, name: string) {
        //@ts-ignore
        window.showSaveFilePicker ? this.SaveFileByWindow(data, name) : this.SaveFileByDocument(data, name);
    }

    private async OpenFileByWindow() {
        const pickerOpts = {
            // types: [
            //     {
            //         description: 'Images',
            //         accept: {
            //             'image/*': ['.png', '.gif', '.jpeg', '.jpg']
            //         }
            //     },
            // ],
            //excludeAcceptAllOption: true,
            multiple: false
        };
        //@ts-ignore
        let arrFileHandle = await window.showOpenFilePicker(pickerOpts);
        let file = await arrFileHandle[0].getFile();
        return file as File;
    }
    private async OpenFileByDocument() {
        return new Promise<File>((s, f) => {
            const i = document.createElement("input");
            i.type = "file";
            i.addEventListener("change", () => {
                if (i.files) {
                    let file = i.files[0];
                    s(file);
                }
            });
            i.click();
        });
    }
    private async SaveFileByWindow(data: any, name: string) {
        const opts = {
            // types: [{
            //     description: 'Text file',
            //     accept: { 'text/plain': ['.txt'] },
            // }],
            suggestedName: name
        };
        //@ts-ignore
        let fileHandle = await window.showSaveFilePicker(opts);
        //const fileData = await fileHandle.getFile();
        const writable = await fileHandle.createWritable();
        await writable.write(JSON.stringify(data));
        await writable.close();
    }
    private async SaveFileByDocument(data: any, name: string) {
        let fileName = window.prompt("saveProject", name);
        if (!fileName) {
            return;
        }
        const urlObject = window.URL || window.webkitURL || window;
        //const exportBlob = new Blob([JSON.stringify(data, null, 4)]);
        const exportBlob = new Blob([JSON.stringify(data)]);
        const saveLink = document.createElement("a");
        saveLink.href = urlObject.createObjectURL(exportBlob);
        saveLink.download = fileName;
        saveLink.click();
    }
}